<template>
  <div class="app-container">
    <el-card title="邮件日志管理">
      <!-- 操作按钮区域 -->
      <div class="table-operations">
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">
          批量删除
        </el-button>
        <el-button type="success" icon="el-icon-download" @click="handleExport">
          导出日志列表
        </el-button>
        <el-input
          v-model="searchForm.toEmail"
          placeholder="输入收件人邮箱搜索"
          style="width: 240px; margin-left: 10px"
          prefix-icon="el-icon-search"
        />
      </div>

      <!-- 搜索条件区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="邮件主题">
          <el-input v-model="searchForm.subject" placeholder="请输入邮件主题" style="width: 200px"/>
        </el-form-item>
        <el-form-item label="发送状态">
          <el-select v-model="searchForm.sendSuccess" placeholder="请选择发送状态" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="成功" :value="true"></el-option>
            <el-option label="失败" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 邮件日志表格 -->
      <el-table
        :data="emailLogList"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="fromEmail" label="发件人" width="180"></el-table-column>
        <el-table-column prop="toEmail" label="收件人" width="180"></el-table-column>
        <el-table-column prop="subject" label="邮件主题" width="250" show-overflow-tooltip></el-table-column>
        <el-table-column prop="contentSummary" label="内容摘要" width="300" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sendSuccess" label="发送状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.sendSuccess" class="status-success">成功</span>
            <span v-else class="status-error">失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="sendTime" label="发送时间" width="180">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.sendTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sendDuration" label="发送耗时(ms)" width="120"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="handleView(scope.row)">
              查看详情
            </el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 查看详情弹窗 -->
    <el-dialog title="邮件日志详情" :visible.sync="detailDialogVisible" width="600px">
      <el-form :model="detailForm" label-width="100px" size="small">
        <el-form-item label="发件人">
          <el-input v-model="detailForm.fromEmail" disabled></el-input>
        </el-form-item>
        <el-form-item label="收件人">
          <el-input v-model="detailForm.toEmail" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮件主题">
          <el-input v-model="detailForm.subject" disabled></el-input>
        </el-form-item>
        <el-form-item label="内容摘要">
          <el-input v-model="detailForm.contentSummary" type="textarea" :rows="4" disabled></el-input>
        </el-form-item>
        <el-form-item label="发送状态">
          <el-input v-model="sendStatusText" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="!detailForm.sendSuccess" label="错误信息">
          <el-input v-model="detailForm.errorMessage" type="textarea" :rows="3" disabled></el-input>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-input v-model="formattedSendTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="发送耗时">
          <el-input v-model="sendDurationText" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import emailLogApi from '@/api/warn/emailLog'

export default {
  name: 'EmailLogList',
  data() {
    return {
      emailLogList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      searchForm: {
        toEmail: '',
        subject: '',
        sendSuccess: ''
      },
      dateRange: [],
      multipleSelection: [],
      detailDialogVisible: false,
      detailForm: {}
    }
  },
  created() {
    this.loadEmailLogList()
  },
  computed: {
    sendStatusText() {
      return this.detailForm.sendSuccess ? '成功' : '失败'
    },
    formattedSendTime() {
      return this.formatDate(this.detailForm.sendTime)
    },
    sendDurationText() {
      return this.detailForm.sendDuration + 'ms'
    }
  },
  methods: {
    // 加载邮件日志列表
    loadEmailLogList() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        toEmail: this.searchForm.toEmail,
        subject: this.searchForm.subject,
        sendSuccess: this.searchForm.sendSuccess,
        startTime: this.dateRange[0] || '',
        endTime: this.dateRange[1] || ''
      }

      emailLogApi.getEmailLogList(params)
        .then(response => {
          this.emailLogList = response.data.list
          this.total = response.data.total
        })
        .catch(error => {
          this.$message.error('加载邮件日志列表失败: ' + (error.message || '网络异常'))
        })
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadEmailLogList()
    },

    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        toEmail: '',
        subject: '',
        sendSuccess: ''
      }
      this.dateRange = []
      this.currentPage = 1
      this.loadEmailLogList()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.loadEmailLogList()
    },

    // 页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadEmailLogList()
    },

    // 选择项变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查看详情
    handleView(row) {
      emailLogApi.getEmailLogDetail(row.id)
        .then(response => {
          this.detailForm = response.data
          this.detailDialogVisible = true
        })
        .catch(error => {
          this.$message.error('获取详情失败: ' + (error.message || '网络异常'))
        })
    },

    // 删除单个日志
    handleDelete(row) {
      this.$confirm(`确定要删除这条邮件日志吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        emailLogApi.deleteEmailLog(row.id)
          .then(() => {
            this.$message.success('删除成功')
            this.loadEmailLogList()
          })
          .catch(error => {
            this.$message.error('删除失败: ' + (error.message || '网络异常'))
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 批量删除
    handleBatchDelete() {
      const ids = this.multipleSelection.map(item => item.id)
      this.$confirm(`确定要删除选中的 ${ids.length} 条邮件日志吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        emailLogApi.batchDeleteEmailLog(ids)
          .then(() => {
            this.$message.success('批量删除成功')
            this.loadEmailLogList()
          })
          .catch(error => {
            this.$message.error('批量删除失败: ' + (error.message || '网络异常'))
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 导出日志
    handleExport() {
      emailLogApi.exportEmailLog()
        .then(response => {
          const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          const date = new Date()
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const fileName = `邮件日志列表_${year}${month}${day}.xlsx`
          a.download = fileName
          a.click()
          URL.revokeObjectURL(url)
          this.$message.success('导出成功')
        })
        .catch(error => {
          this.$message.error('导出失败: ' + (error.message || '网络异常'))
        })
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hour = String(d.getHours()).padStart(2, '0')
      const minute = String(d.getMinutes()).padStart(2, '0')
      const second = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }
  },
  // 搜索防抖
  watch: {
    'searchForm.toEmail'(val) {
      this.handleSearch()
    }
  }
}
</script>

<style scoped>
.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.status-success {
  color: #67c23a;
}

.status-error {
  color: #f56c6c;
}
</style>
